<template>
  <view class="update-v" v-if="modalVisible">
    <view class="update" v-if="upData">
      <image class="update-img" src="../../static/images/update-img.png" mode="widthFix"></image>
      <view class="update-tips">
        <view class="update-basic-info">
          <view class="update-tips-i">最新版本：v{{upData.version}}</view>
          <view class="update-tips-i">版本大小：{{upData.versionSize}}M</view>
        </view>
        <view class="update-tips-content-title">更新内容：</view>
        <!-- upgradationType: 1:普通更新 2:强制更新 -->
        <scroll-view class="update-content" :style="upData.upgradationType == 2 ? 'height: 396rpx;':'height: 500rpx;'" scroll-y="true" >
          <view class="scroll-view-text">
            {{upData.promptContent.replace(/\\r\\n/g, '<br/>')}}
          </view>
        </scroll-view>
      </view>
      <block v-if="!hotFixStart">
        <view class="update-buttons">
          <view @click="updateNow">立即更新</view>
          <view @click="close" v-if="upData.upgradationType == 2">下次再说</view>
        </view>
      </block>
      <block v-if="hotFixStart">
        <view class="progress">
          <view class="progress-v">
            <view class="progress-num" :style="'left:' + progressNumLeft + '%;'">{{ progressNum }}%</view>
            <view class="progress-v_top" :style="'width:' + progressNum + '%;'"></view>
            <view class="progress-v_bottom"></view>
          </view>
          <view class="progress-tip_1">新版本正在努力更新中，请稍后···</view>
          <view class="progress-tip_2">更新过程中请保持留在当前界面，不要退出</view>
        </view>
      </block>
    </view>
  </view>
</template>

<script lang="ts" setup>
  import { ref, watch, nextTick } from 'vue'
  import dayjs from 'dayjs'
  import { userStore } from '@/stores'
  const userInfoStore = userStore()

  // const emits = defineEmits(['close', 'rightClick', 'change'])

  // const props = defineProps({
  //   btnText: {
  //     type: String,
  //     default: '确认',
  //   },
  // })
  const upData = ref(null)
  const modalVisible = ref(false)
  const hotFixStart = ref(false)
  const progressNum = ref(11)
  const progressNumLeft = ref(1)

  const tipStorge = ref() //提示几次
  const dayStorge = ref() //日期缓存
  const getday = ref() //今日

  const emits = defineEmits(['close'])

  const close = () => {
    modalVisible.value = false
    emits('close', 1)
    // -有建议更新的需求时，连续三次每天首次进入APP时，提示用户更新，3天过后不在提醒，包含发布当天
    if(!tipStorge.value){
      uni.setStorageSync('day_storge', getday.value);
      uni.setStorageSync('day_tip', 1);
    }else if(tipStorge.value == 1 && getday.value!=dayStorge.value){
      uni.setStorageSync('day_storge', getday.value);
      uni.setStorageSync('day_tip', 2);
    }else if(tipStorge.value == 2 && getday.value!=dayStorge.value){
      uni.setStorageSync('day_storge', getday.value);
      uni.setStorageSync('day_tip', 3);
    }else if(tipStorge.value == 3 && getday.value!=dayStorge.value){
      uni.setStorageSync('day_storge', getday.value);
      uni.setStorageSync('day_tip', 4);
    }
  }

  let app_version = ''
  const show = (r) => {
    app_version = r.result.version
    tipStorge.value = uni.getStorageSync('day_tip')
    dayStorge.value = uni.getStorageSync('day_storge')
    getday.value = dayjs().format("YYYY-MM-DD")

    // 如果是需求连续3天的话,获取的今日 减 缓存的日期差值 给day_tip自动赋值  大于3则不再提示
    if(!modalVisible.value){
      // console.log('☁ ☁ ☁')
      upData.value = r.result
      // 获取的今日=缓存的日期 && 推荐更新   不提示
      if(getday.value==dayStorge.value && upData.value.upgradationType == 2){
        modalVisible.value = false
        emits('close', 1)
        uni.setStorageSync('updateNow', 1);
        return
      }
      // 关闭次数day_tip>3 && 推荐更新  不提示
      if(tipStorge.value == 4 && upData.value.upgradationType == 2){
        modalVisible.value = false
        emits('close', 1)
        uni.setStorageSync('updateNow', 1);
        return
      }

      // 更新关闭状态下不弹窗
      if(upData.value.status == 2){
        return false
      }

      modalVisible.value = true
      uni.removeStorageSync('day_storge')
      uni.removeStorageSync('updateNow') //如果不是推荐更新的话，清除不更新标记
      if(upData.value.upgradationType != 2){
        uni.removeStorageSync('day_tip') //如果不是推荐更新的话，清除标记次数
      }
    }
  }

  watch(
    () => modalVisible.value,
    (val) => {
      if (val) {
        uni.hideTabBar()
      } else {
        uni.showTabBar()
      }
    },
  )

  // 点击升级
  const updateNow = () => {
  	if(upData.value.updateWay == 3){
      console.log(JSON.stringify(plus.device.vendor))
  		var appurl;
  		if (plus.os.name=="Android") {
        if(plus.device.vendor == 'HUAWEI'){
          appurl = "appmarket://details?id=com.qccw.uni";
          plus.runtime.openURL(appurl, function(res) {
          	console.log(res);
          });
        }else{
          // 除华为外的品牌会跳转浏览器下载整包(转为整包更新)
          if(!upData.value.downloadUrl){
            uni.showToast({
            	title: '请联系客服是否已上架该应用',
            	icon: 'none'
            });
            return false
          }
          var qccwUrl = upData.value.downloadUrl
          plus.runtime.openURL(qccwUrl);
        }
  		}else{
        let appleId = '6473774460' //app对应的appleId
        plus.runtime.launchApplication({
          action: `itms-apps://itunes.apple.com/cn/app/id${appleId}?mt=8`
        }, function(e) {
            uni.showToast({
            	title: '如果失败，请联系客服AppStore是否已上架该应用',
            	icon: 'none'
            });
        });
      }
  	}
  	if(upData.value.updateWay == 1){
      if (plus.os.name=="Android") {
        var qccwUrl = upData.value.downloadUrl
        plus.runtime.openURL(qccwUrl);
      }else{
        uni.showToast({
        	title: '请到AppStore进行更新',
        	icon: 'none'
        });
      }
  	}
  	if(upData.value.updateWay == 2){
      if(plus.os.name=="Android"){
        downWgt(upData.value.hotPatchUrl)
      }else{
        downWgt(upData.value.hotPatchIosUrl)
      }
  	}
  }

  // 下载
  const downWgt = (path) => {
    hotFixStart.value = true
  	const downloadTask = uni.downloadFile({
  		url: path,
  		success: (downloadResult) => {
  			if (downloadResult.statusCode === 200) {
  				plus.runtime.install(downloadResult.tempFilePath, {
  					force: true
  				}, function() {
  					plus.nativeUI.alert(`版本${app_version}更新完成！`, function() {
              // 清空商户配置；TODO 用户权限重构
              userInfoStore.enterpriseDetail = {}
              userInfoStore.permissons_need_refresh = true
              plus.runtime.restart();
  					});
  				}, function(e) {
  					plus.nativeUI.toast("更新失败，请稍后再试");
  				});
  			}
  		}
  	})
    // 进度
  	downloadTask.onProgressUpdate((res) => { //下载文件的进度
      console.log('下载进度:' + res.progress)
  		// console.log('downloatTask',res);
  		// console.log(res)
      nextTick(()=>{
        // res.totalBytesWritten; //当前下载大小
        // res.totalBytesExpectedToWrite; //
        if ( res.progress < 10 ) {
          progressNum.value = 11  //进度最小设置为11%，数字能显示在橙色上
          progressNumLeft.value = 1  //距左最小设置为2%，数字能显示在灰色上
        }else if( res.progress > 90 ) {
          progressNumLeft.value = 89  //距右最大设置为89%，避免数字超出进度条显示
          progressNum.value = res.progress; //当前下载比例
        }else{
          progressNum.value = res.progress; //当前下载比例
          progressNumLeft.value = res.progress - 10
        }
      })
  	});
  }

  defineExpose({ show })

</script>

<style lang="scss" scoped>
  .update-v{
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .update{
    width: 654rpx;
    height: 1002rpx;
    position: relative;
    animation-name: fade;
    animation-duration: .1s;
    animation-timing-function: linear
  }
  @keyframes fade {
    0% {
      opacity: 0;
      transform: scale(0.8)
    }
    100% {
      opacity: 1;
      transform: scale(1)
    }
  }
  .update-img{
    width: 654rpx;
    height: 1002rpx;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
  }
  .update-tips{
    font-size: 30rpx;
    color: #191C27;
    font-weight: 400;
    position: absolute;
    top: 224rpx;
    left: 40rpx;
    right: 40rpx;
    z-index: 2;
    .update-basic-info {
      display: flex;
      .update-tips-i:first-child {
        margin-right: 26rpx;
      }
    }
  }
  .update-tips-i {
    line-height: 44rpx;
  }
  .update-tips-content-title {
    margin-top: 16rpx;
  }
  scroll-view{
    height: 234rpx;
  }
  .scroll-view-text{
    line-height: 1.5;
    white-space: pre-line;
  }
  .update-buttons{
    position: absolute;
    left: 40rpx;
    right: 40rpx;
    bottom: 40rpx;
    z-index: 2;
  }
  .update-buttons view:nth-child(1){
    background: #FD8538;
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    border: 1px solid #FD8538;
    color: #FFFFFF;
    border-radius: 4rpx;
  }
  .update-buttons view:nth-child(2){
    background: #ffffff;
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    border: 1px solid #FD8538;
    color: #FD8538;
    border-radius: 4rpx;
    margin-top: 24rpx;
  }
  .progress{
    position: absolute;
    left: 40rpx;
    right: 40rpx;
    bottom: 66rpx;
    z-index: 2;
  }
  .progress-v{
    position: relative;
    margin-bottom: 56rpx;
    .progress-num{
      position: absolute;
      top: 0;
      font-size: 24rpx;
      color: #ffffff;
      font-weight: 400;
      z-index: 3;
    }
    .progress-v_top{
      position: absolute;
      width: 100%;
      height: 32rpx;
      background-image: linear-gradient(to right, #FFB700, #FF4500);
      left: 0;
      top: 0;
      z-index: 2;
      border-radius: 40rpx;
    }
    .progress-v_bottom{
      position: absolute;
      width: 100%;
      height: 32rpx;
      background-color: #EDEDED;
      left: 0;
      top: 0;
      z-index: 1;
      border-radius: 40rpx;
    }
  }
  .progress-tip_1{
    width: 100%;
    text-align: center;
    font-size: 24rpx;
    color: #8491A8;
    font-weight: 400;
    margin-bottom: 24rpx;
  }
  .progress-tip_2{
    width: 100%;
    text-align: center;
    font-size: 24rpx;
    color: #FF4A00;
    font-weight: 400;
  }
</style>
